package com.yunxin.admin.system.api.system;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunxin.admin.system.application.UserApplicationService;
import com.yunxin.admin.system.application.UserQueryService;
import com.yunxin.admin.system.application.command.AddUserCommand;
import com.yunxin.admin.system.application.command.UpdateReceivingStatusCommand;
import com.yunxin.admin.system.application.command.UpdateUserCommand;
import com.yunxin.admin.system.application.command.UserPageCommand;
import com.yunxin.admin.system.application.dto.*;
import com.yunxin.admin.system.domain.model.user.UserMerchantRepository;
import com.yunxin.admin.system.infra.common.constant.ExcelConstants;
import com.yunxin.admin.system.infra.common.constant.SecurityConstants;
import com.yunxin.admin.system.infra.common.constant.SystemConstants;
import com.yunxin.admin.system.infra.common.enums.AdminResultCode;
import com.yunxin.admin.system.infra.common.util.ExcelUtils;
import com.yunxin.admin.system.infra.framework.resubmit.Resubmit;
import com.yunxin.admin.system.infra.framework.security.util.SecurityUtils;
import com.yunxin.admin.system.infra.framework.syslog.AutoLog;
import com.yunxin.admin.system.domain.model.user.listener.UserImportListener;
import com.yunxin.admin.system.infra.persistence.mapper.SysRoleMapper;
import com.yunxin.common.exception.BusinessException;
import com.yunxin.common.result.PageResult;
import com.yunxin.common.result.Result;
import com.yunxin.common.result.ResultCode;
import com.yunxin.core.admin.service.AdminUserService;
import com.yunxin.core.application.service.TeamService;
import com.yunxin.core.application.service.UserTeamShipService;
import com.yunxin.core.domain.model.team.Team;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * 用户控制器
 *
 * @author zero°
 * @since 2023-05-22
 */
@Tag(name = "02.用户接口")
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class SysUserController {

    private final UserApplicationService userService;

    private final UserQueryService userQueryService;

    private final UserMerchantRepository userMerchantRepository;

    private final TeamService teamService;
    @Autowired
    private AdminUserService adminUserService;


    @Operation(summary = "用户分页列表", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/page")
    public PageResult<UserPageDTO> getUserPage(@ParameterObject UserPageCommand command) {
        if (!SecurityUtils.X.isRoot()){
            Long userId = SecurityUtils.X.getUser().getUserId();
            if (!SecurityUtils.X.isBokeMerchantUser()&&!SecurityUtils.X.isBokeTeamUser()){
                throw new BusinessException("权限不够");
            }
            if(ObjectUtils.isEmpty(command.getTeamIdList())) {
                if (SecurityUtils.X.isBokeMerchantUser()){
                    //商户管理员只能看自己所有团队下的账户信息
                    Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
                    List<Team> teams = teamService.getTeamList(merchantId);
                    if (CollUtil.isEmpty(teams)){
                        return PageResult.success(Collections.emptyList(),0);
                    }
                    List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
                    command.setTeamIdList(teamIds);
                }else if (SecurityUtils.X.isBokeTeamUser()) {
                    //团队管理员只能看自己团队下的账户信息
                    List<Team> teams = teamService.getTeamListByUserId(userId);
                    if (CollUtil.isEmpty(teams)){
                        return PageResult.success(Collections.emptyList(),0);
                    }
                    List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
                    command.setTeamIdList(teamIds);
                }
            }
        }else {
            if(ObjectUtils.isEmpty(command.getTeamIdList())) {
                if (!ObjectUtils.isEmpty(command.getMerchantId())){
                    List<Team> teams = teamService.getTeamList(command.getMerchantId());
                    if (CollUtil.isEmpty(teams)){
                        return PageResult.success(Collections.emptyList(),0);
                    }
                    List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
                    command.setTeamIdList(teamIds);
                }else {
                    List<Team> teams = teamService.getAllTeamList();
                    if (CollUtil.isEmpty(teams)){
                        return PageResult.success(Collections.emptyList(),0);
                    }
                    List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
                    command.setTeamIdList(teamIds);
                }
            }
        }
        if (ObjectUtils.isEmpty(command.getTeamIdList())){
            return PageResult.success(null, 0);
        }
        Page<UserPageDTO> result = userQueryService.getUserPage(command);
        return PageResult.success(result.getRecords(), result.getTotal());
    }

    @Operation(summary = "新增用户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping
    //@PreAuthorize("@ss.hasPerm('sys:user:add')")
    @Resubmit
    @AutoLog(value = "新增用户")
    public Result<Boolean> saveUser(@RequestBody @Valid AddUserCommand command) {
        checkRole();
        Long userId = SecurityUtils.X.getUser().getUserId();
        Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
        command.setMerchantId(merchantId);
        boolean result = userService.saveUser(command);
        return Result.judge(result);
    }


    @Operation(summary = "用户表单数据", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/{userId}/form")
    public Result<UserDetailDTO> getUserForm(@Parameter(description = "用户ID") @PathVariable Long userId) {
        UserDetailDTO userDetailDTO = userQueryService.getUserInfoByIdAndTeamId(userId);
        return Result.success(userDetailDTO);
    }

    @Operation(summary = "修改用户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PutMapping(value = "/{userId}")
    //@PreAuthorize("@ss.hasPerm('sys:user:edit')")
    @Resubmit
    @AutoLog(value = "修改用户")
    public Result<Boolean> updateUser(@RequestBody @Validated UpdateUserCommand command) {
        checkRole();
        boolean result = userService.updateUser(command);
        return Result.judge(result);
    }

//    @Operation(summary = "删除用户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @DeleteMapping("/{ids}")
//    //@PreAuthorize("@ss.hasPerm('sys:user:delete')")
//    @AutoLog(value = "删除用户")
//    public Result<Boolean> deleteUsers(@Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids) {
//        checkRole();
//        boolean result = userService.deleteUsers(ids);
//        return Result.judge(result);
//    }

    @Operation(summary = "修改用户密码", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PatchMapping(value = "/{userId}/password")
    public Result<Boolean> updatePassword(@Parameter(description = "用户ID") @PathVariable Long userId,
            @RequestParam String password) {
        boolean result = userService.updatePassword(userId, password);
        return Result.judge(result);
    }

    @Operation(summary = "修改用户状态", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PatchMapping(value = "/{userId}/status")
    @AutoLog(value = "修改用户状态")
    public Result<Boolean> updateUserStatus(@Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "用户状态(1:启用;0:禁用)") @RequestParam Integer status) {
        checkRole();
        boolean result = userService.updateStatus(userId, status);
        return Result.judge(result);
    }

    @Operation(summary = "修改用户接单状态", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PatchMapping(value = "/{userId}/receivingStatus")
    @AutoLog(value = "修改用户状态")
    public Result<Boolean> updateUserReceivingStatus(@Parameter(description = "用户ID") @PathVariable Long userId,
                                                     @Parameter(description = "团队id") @RequestParam Long temaId,
                                            @Parameter(description = "用户状态(1:启用;0:禁用)") @RequestParam Integer receivingStatus) {
        checkRole();
        boolean result = userService.updateUserReceivingStatus(userId,temaId, receivingStatus);
        return Result.judge(result);
    }

    @Operation(summary = "一键修改商户或团队用户接单状态", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping(value = "/updateReceivingStatus")
    //@PreAuthorize("@ss.hasPerm('sys:user:merchant:update:status')")
    @Resubmit
    @AutoLog(value = "一键修改商户或团队用户接单状态")
    public Result updateReceivingStatus(@RequestBody @Validated UpdateReceivingStatusCommand command) {
        checkRole();
        Long userId = SecurityUtils.X.getUser().getUserId();
        if(ObjectUtils.isEmpty(command.getTeamIdList())) {
            if (SecurityUtils.X.isBokeMerchantUser()){
                //商户管理员只能看自己所有团队下的账户信息
                Long merchantId = userMerchantRepository.selectMerchantIdByUserId(userId);
                List<Team> teams = teamService.getTeamList(merchantId);
                if (CollUtil.isEmpty(teams)){
                    return Result.success();
                }
                List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
                command.setTeamIdList(teamIds);
            }else if (SecurityUtils.X.isBokeTeamUser()) {
                //团队管理员只能看自己团队下的账户信息
                List<Team> teams = teamService.getTeamListByUserId(userId);
                if (CollUtil.isEmpty(teams)){
                    return Result.success();
                }
                List<Long> teamIds = teams.stream().map(i -> i.getId().longValue()).toList();
                command.setTeamIdList(teamIds);
            }
        }
        userService.updateReceivingStatus(command);
        return Result.success();
    }

    @Operation(summary = "获取当前登录用户信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping("/me")
    public Result<UserInfoDTO> getUserLoginInfo() {
        UserInfoDTO userInfoDTO = userQueryService.getUserLoginInfo();
        return Result.success(userInfoDTO);
    }

    @Operation(summary = "获取自己个人信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @GetMapping(value = "/getOwnUser")
    @AutoLog(value = "获取自己个人信息")
    public Result<UserOwnDetailDTO> getOwnUser() {
        return Result.success(userQueryService.getOwnUserById(SecurityUtils.X.getUserId()));
    }

    @Operation(summary = "修改自己个人密码", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping(value = "/updateOwnUserPassword")
    @AutoLog(value = "修改自己个人信息")
    public Result<Boolean> updateOwnUserPassword(@RequestParam String password) {
        boolean result = userService.updatePassword(SecurityUtils.X.getUserId(), password);
        return Result.judge(result);
    }

    @Operation(summary = "修改自己个人信息", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
    @PostMapping(value = "/updateOwnUser")
    @AutoLog(value = "修改自己个人信息")
    public Result<Map<String, String>> updateOwnUser(@RequestBody @Validated UpdateUserDetailDTO userDetailDTO) {
        userDetailDTO.setId(SecurityUtils.X.getUserId());
        Map<String, String> map = userService.updateOwnUser(userDetailDTO);
//        if (!ObjectUtils.isEmpty(map)&&map.size()>0){
//            return Result.result(ResultCode.BINDING_WECHAT_ERROR,map);
//        }
        return Result.success(map);
    }

//    @Operation(summary = "用户导入模板下载", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping("/template")
//    public void downloadTemplate(HttpServletResponse response) throws IOException {
//        String fileName = "用户导入模板.xlsx";
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        String fileClassPath = ExcelConstants.EXCEL_TEMPLATE_DIR + File.separator + fileName;
//        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);
//        ServletOutputStream outputStream = response.getOutputStream();
//        ExcelWriter excelWriter = EasyExcelFactory.write(outputStream).withTemplate(inputStream).build();
//        excelWriter.finish();
//    }
//
//    @Operation(summary = "导入用户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @PostMapping("/_import")
//    public Result<String> importUsers(@Parameter(description = "部门ID") Long deptId, MultipartFile file) throws IOException {
//        UserImportListener listener = new UserImportListener(deptId);
//        String msg = ExcelUtils.importExcel(file.getInputStream(), UserImportDTO.class, listener);
//        return Result.success(msg);
//    }
//
//    @Operation(summary = "导出用户", security = {@SecurityRequirement(name = SecurityConstants.TOKEN_KEY)})
//    @GetMapping("/_export")
//    public void exportUsers(UserPageCommand command, HttpServletResponse response) throws IOException {
//        String fileName = "用户列表.xlsx";
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
//        List<UserExportDTO> exportUserList = userQueryService.listExportUsers(command);
//        EasyExcelFactory.write(response.getOutputStream(), UserExportDTO.class).sheet("用户列表")
//                .doWrite(exportUserList);
//    }

    /**
     * 判断登录用户权限，必须是商户管理员角色或者团队管理员角色才允许操作
     */
    private void checkRole(){
        if (SecurityUtils.X.getRoles().size() < 1) {
            throw new BusinessException(AdminResultCode.USER_MERCHANT_ROLE_ERROR);
        }
        if (!SecurityUtils.X.isBokeMerchantUser() && !SecurityUtils.X.isBokeTeamUser()) {
            throw new BusinessException(AdminResultCode.ADMIN_MERCHANT_ROLE_ERROR);
        }
    }

    /**
     * 商户管理员角色配置
     * @param roleIds roleIds
     * @param merchantId merchantId
     */
//    private void merchantAdminCheck(List<Long> roleIds, Long merchantId){
//        Long roleId = sysRoleMapper.getRoleIdByCode(SystemConstants.BOKE_MERCHANT_ADMIN);
//        if (roleIds.contains(roleId) && roleIds.size() != 1) {
//            throw new BusinessException(AdminResultCode.MERCHANT_ADMIN_ROLE_ERROR);
//        }
//        if (roleIds.contains(roleId) && (Objects.isNull(merchantId) || merchantId == 0)) {
//            throw new BusinessException(AdminResultCode.MERCHANT_ADMIN_ERROR);
//        }
//        if (!roleIds.contains(rol  eId) && (Objects.nonNull(merchantId) && merchantId > 0)) {
//            throw new BusinessException(AdminResultCode.USER_ROLE_MERCHANT_ERROR);
//        }
//    }
}
